/***************************************************
 ** @Desc : This file for 商户条件控制
 ** @Time : 2019.04.13 9:42 
 ** @Author : Joker
 ** @File : merchant_factor
 ** @Last Modified by : Joker
 ** @Last Modified time: 2019.04.13 9:42
 ** @Software: GoLand
****************************************************/
package condition

import (
	"math/rand"
	"recharge/controllers/implement"
	"recharge/models"
	"recharge/sys"
	"recharge/utils"
	"time"
)

type MerchantFactor struct{}

var merchantMdl = models.Merchant{}
var merchantImpl = implement.MerchantImpl{}

// 从所有可充值的商户中选择单个商户
func (*MerchantFactor) QueryOneMerchantForRecharge() models.Merchant {
	in := make(map[string]interface{})
	list := merchantMdl.SelectAllMerchantBy(in)

	//随机种子
	rand.Seed(time.Now().UnixNano())
	randInt := rand.Intn(len(list))

	return list[randInt]
}

// 从所有可代付的商户中选择单个商户
func (*MerchantFactor) QueryOneMerchantForPay(amount string) (m models.Merchant) {
	in := make(map[string]interface{})
	in["usable_amount__gte"] = amount //可用余额不小于提现金额

	list := merchantMdl.SelectAllMerchantBy(in)

	// 若找不到可用通道，则更新全部通道余额
	if len(list) <= 0 {
		var msg = utils.FAILED_STRING
		var flag = utils.FAILED_FLAG

		re := make(map[string]interface{})
		reList := merchantMdl.SelectAllMerchantBy(re)
		for _, v := range reList {
			switch v.ChannelType {
			case utils.XF:
				_, flag = merchantImpl.UpdateMerchantAmount(v, msg, flag)
				if flag < 0 {
					sys.LogError("商户：", v.MerchantName, "自动更新余额失败，请手动更新")
				} else {
					sys.LogInfo("商户：", v.MerchantName, "代付余额不足，现已自动更新")
				}
			}
		}

		list = merchantMdl.SelectAllMerchantBy(in)
	}

	// 通道余额不足，需充值
	if len(list) <= 0 {
		sys.LogInfo("商户代付余额可能不足，请手动确认代付余额后，充值备付金")
		return
	}

	//随机种子
	rand.Seed(time.Now().UnixNano())
	randInt := rand.Intn(len(list))

	return list[randInt]
}
